import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { List, Image, Search, Tag } from 'react-vant'
import { useNavigate } from 'react-router-dom'

interface PageConfig {
	pageCode?: number
	pageSize?: number
}

export interface ListItemType {
	"tilte": string,
	"image": string,
	"desc": string,
	"id": number | string
}


const Index = () => {
	const [list, setList] = useState<ListItemType[]>([]);
	const [finished, setFinished] = useState(false)
	const [pageCode, setPageCode] = useState(1)
	const navigate = useNavigate()
	// 请求数据方法
	const fetchList = async (params?: PageConfig) => {
		const resp = await axios.get('/api/list', { params });
		return resp.data
	}

	// 当滑动到底部的时候。 onload 执行
	const onLoad = async () => {
		// 请求数据
		const { code, data } = await fetchList({ pageCode });
		// 判断总数据是否超过100条
		if (list.length >= 100) {
			// 超过设置数据请求完成， 不需要再一次请求后台数据了
			setFinished(true)
		} else {
			// 保存数据
			setList([...list, ...data]);
			// 分页+1
			setPageCode(pageCode + 1)
		}

	}
	return (
		<div className='home'>
			<div className='header'>
				<Search className='search' onFocus={() => navigate('/search')}></Search>
				<div className='header-tag'>
					<Tag type="primary" onClick={() => navigate('/sign')}>签到</Tag>
					<Tag type="success" onClick={() => navigate('/tags')}>标签</Tag>
				</div>
			</div>
			<List onLoad={onLoad} finished={finished} finishedText="没有更多数据了！！">
				{
					list.map(v => {
						return (
							<dl key={v.id}>
								<dt>
									<Image src={v.image} alt="" lazyload width={120} height={80} />
								</dt>
								<dd>
									<h3>{v.tilte}</h3>
									<p>{v.desc}</p>
								</dd>
							</dl>
						)
					})
				}
			</List>
		</div>
	)
}

export default Index